#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define SIZE 1028
#define FORMAT "[%s@%s %s]# "
#define MAX 128
char*argv[MAX];
int argc=0;
const char* getUserName()
{
  const char*name=getenv("USER");
  return name==NULL? "None":name;
}

const char*getHostName()
{
  const char*hostname=getenv("HOSTNAME");
  return hostname==NULL? "None":hostname;
}
const char*getpwd()
{
  const char*pwd=getenv("PWD");
  return pwd==NULL?"None":pwd;
}
  void MakeCommandLine(char cmd_prompt[], int size)
{
  snprintf(cmd_prompt,size,FORMAT,getUserName(),getHostName(),getpwd());
}
  void PrintCommandPrompt()//打印命令行提示符
{
  char prompt[SIZE];
  MakeCommandLine(prompt,sizeof(prompt));
  printf("%s",prompt);
  fflush(stdout);
}
bool GetCommandLine(char *out, int size)//获取用户输入的命令转化成字符串存入数组
{
    char*c=fgets(out,size,stdin);
    if(c==NULL) return false;
    out[strlen(out)-1]=0;
    if(strlen(out)==0) return false;
    return true;
}
bool CommandParse(char *commandline)//命令行分析
{
#define EMP " "
  argc=0;
  argv[argc++]=strtok(commandline,EMP);
  while((bool)(argv[argc++]=strtok(nullptr,EMP)));
  argc--;
  return true;
}
  int Execute()
{
  pid_t id=fork();
  if(id==0)
  {
    execvp(argv[0],argv);
    exit(1);
  }
  waitpid(id,nullptr,0);
  return 0;
}
int main()
{
  while(true)
  {
  //输出命令行提示符
  PrintCommandPrompt();
  //获取用户输入到的命令
  char commandline[SIZE];
  if(!GetCommandLine(commandline,sizeof(commandline)))
    continue;
   // 3. 命令行分析 "ls -a -l" -> "ls" "-a" "-l" 切割命令行输入的字符
  CommandParse(commandline);
  // 4. 执行命令
        Execute();
  }
  return 0;
}
